package com.saicmotor.pay.view.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.saicmotor.pay.AuthResult;
import com.saicmotor.pay.PayManager;
import com.saicmotor.pay.PayResult;
import com.saicmotor.pay.R;
import com.saicmotor.pay.base.BaseActivity;
import com.saicmotor.pay.com.Constance;
import com.saicmotor.pay.com.Constant;
import com.saicmotor.pay.databinding.LayoutCashierBinding;
import com.saicmotor.pay.error.ErrorInfo;
import com.saicmotor.pay.http.Entity.QueryTranStatusEntity;
import com.saicmotor.pay.http.Entity.appendPayRecordEntity;
import com.saicmotor.pay.http.ResultCallback;
import com.saicmotor.pay.http.request.appendPayRecordReq;
import com.saicmotor.pay.util.HttpKit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Route(path = Constance.ACTIVITY_CASHIER)
public class CashierActivity extends BaseActivity implements View.OnClickListener {
    LayoutCashierBinding binding;
    String url = "https://acp.z-onesoftware.com/payment/public/trans/appendpayrecord/v1";

    @Autowired(name = "transId")
    String transId;
    @Autowired(name = "platformMerchId")
    String platformMerchId;
    @Autowired(name = "merchOrderId")
    String merchOrderId;
    @Autowired(name = "userId")
    String userId;
    @Autowired(name = "userName")
    String userName;
    @Autowired(name = "orderAmt")
    Float orderAmt;
    @Autowired(name = "transAmt")
    Float transAmt;
    @Autowired(name = "goodsDescription")
    String goodsDescription;
    @Autowired(name = "payScene")
    String payScene;


    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";

    /**
     * pkcs8 格式的商户私钥。
     * <p>
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     * <p>
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
//                    payResult = new PayResult((Map<String, String>) msg.obj);
//                    /**
//                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
//                     */
//                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
//                    String resultStatus = payResult.getResultStatus();
//                    // 判断resultStatus 为9000则代表支付成功
//                    if (TextUtils.equals(resultStatus, "9000")) {
//                        hideLoading();
//                        Intent intent = new Intent(CashierActivity.this, PaySuccessActivity.class);
//                        intent.putExtra("orderAmt", orderAmt);
//                        startActivity(intent);
//                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        showAlert(CashierActivity.this, "pay_success" + payResult);
//                    } else {
//                        hideLoading();
//                        Intent intent = new Intent(CashierActivity.this, PayFailActivity.class);
//                        intent.putExtra("orderAmt", orderAmt);
//                        startActivity(intent);
//                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(CashierActivity.this, "pay_fail" + payResult);
//                    }
//                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        showAlert(CashierActivity.this, "pay_success" + authResult);
                    } else {
                        // 其他状态值则为授权失败
                        showAlert(CashierActivity.this, "pay_fail" + authResult);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
    @SuppressWarnings("unchecked")
    private PayResult payResult;

    @Override
    public void viewBinding() {
        binding = LayoutCashierBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }

    @Override
    public void initOnCreate(Bundle savedInstanceState) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        binding.tvPay.setOnClickListener(this);
        binding.ivCashierReturn.setOnClickListener(this);
    }

    @Override
    public void initObservable() {

    }

    @Override
    public void onError(ErrorInfo errorInfo) {

    }

    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }

    private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton("confirm", null)
                .setOnDismissListener(onDismiss)
                .show();
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_pay) {
            showLoading(this);
            pay();
        } else if (id == R.id.iv_cashier_return) {
            Intent intent = new Intent();
            if (payResult != null) {
                if (TextUtils.equals(payResult.getResultStatus(), "9000")) {
                    setResult(Constant.PAY_RESULT_OK, intent);
                } else {
                    setResult(Constant.PAY_RESULT_FAIL, intent);
                }
            }
            finish();
        }

    }

    private void pay() {

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {

                String merchOrderId = String.valueOf(System.currentTimeMillis());

                Integer orderAmt = 100;
                JSONObject reqJson = new JSONObject();
                reqJson.put("merchOrderId", merchOrderId);
                reqJson.put("orderAmt", orderAmt);
                reqJson.put("platformMerchId", "m00001");
                reqJson.put("userId", "12");
                Map<String, String> headers = new HashMap<>();
                String getParam = reqJson.toString();
                headers.put("Content-Type", "application/json");
                String url1 = "https://acp.z-onesoftware.com/payment/remote/trans/appendtransrecord/v1";
                String retStr = HttpKit.post(url1, getParam, headers);
                JSONObject retJson = JSONObject.parseObject(retStr);

                String transId = retJson.getJSONObject("data").getString("transId");
                ArrayList<appendPayRecordReq.payDetails> payDetails = new ArrayList<>();
                appendPayRecordReq.payDetails details = new appendPayRecordReq.payDetails();
                details.productCode = "PAY_ZFB_APP";
                details.amt = 100f;
                payDetails.add(details);

                PayManager.getInstance().appendPayRecord(transId, "m00001", merchOrderId, "12", "用户01", 100f, 100f, "花露水", "", "PHONE", payDetails, "127.0.0.1",
                        new ResultCallback<appendPayRecordEntity>() {
                            @Override
                            public void onSuccess(appendPayRecordEntity appendPayRecordEntity) {
                                Runnable ResultRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(CashierActivity.this);
                                        alipay.payV2(appendPayRecordEntity.getPayInfo(), true);

                                    }
                                };
                                Thread ResultThread = new Thread(ResultRunnable);
                                ResultThread.start();
                            }

                            @Override
                            public void onError(String errorCode, String message) {

                            }
                        });


            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

}
